﻿using System.IO;
using System.Text;
using System.Web;

namespace LBSoft.Common.DotNetExt
{
    public static class ExtHttpRequest
    {
        #region GetString
        /// <summary>
        /// 获取参数，当参数值为null的时候，返回string.Empty
        /// </summary>
        /// <param name="source"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetString(this HttpRequest source, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return string.Empty;
            }

            string sValue = source[key];
            if (string.IsNullOrEmpty(sValue))
            {
                return string.Empty;
            }

            return HttpUtility.UrlDecode(sValue.Trim());
        }
        #endregion

        /// <summary>
        /// 返回context.Request输入流转的UTF8字符串
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string ReadAsString(this HttpContext context)
        {

            return context.ReadAsString(Encoding.UTF8);
        }

        /// <summary>
        /// 返回context.Request输入流转的UTF8字符串
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string ReadAsString(this HttpContext context, Encoding encoding)
        {
            using (var reader = new StreamReader(context.Request.InputStream, encoding))
            {
                return reader.ReadToEnd();
            }
        }

    }
}
